﻿
/****** Object:  User Defined Function dbo.ValidateBankRoutingNumber    Script Date: 10/14/2009 10:39:06 PM ******/
CREATE FUNCTION ValidateCreditCardNumber  ( @CreditCardNumber char(40) )  
RETURNS bit AS  
BEGIN 

declare @iCount int
declare @iWeight int
declare @iSum int
declare @iDigit int
declare @iMod as int

set @iWeight = 2
set @iSum = 0

set @CreditCardNumber = rtrim( @CreditCardNumber )
set @iCount = len( @CreditCardNumber )  - 1
while ( @iCount > 0 )
begin
   set @iDigit = @iWeight * ( cast ( substring( @CreditCardNumber, @iCount, 1 )  as int ) )

   set @iSum = @iSum + ( @iDigit / 10 ) + ( @iDigit % 10 )

   if @iWeight = 2
      set @iWeight = 1
   else
      set @iWeight = 2

   set @iCount = @iCount - 1
end

set @iMod = ( 10 - ( @iSum % 10 ) ) % 10

return case when @iMod = cast ( substring( @CreditCardNumber, len( @CreditCardNumber ), 1 ) as int ) then 1 else 0 end
END